package com.yonyou.iuap.jxzy.service;
import com.yonyou.iuap.baseservice.intg.service.GenericIntegrateService;
import com.yonyou.iuap.baseservice.intg.support.ServiceFeature;
import com.yonyou.iuap.iweb.exception.BusinessException;
import com.yonyou.iuap.jxzy.controller.MonitorSampleController;
import com.yonyou.iuap.jxzy.dao.MonitorSampleMapper;
import com.yonyou.iuap.jxzy.entity.MonitorSample;
import com.yonyou.iuap.jxzy.entity.PoundBillVO;
import com.yonyou.iuap.jxzy.servlet.DeviceInfo;
import com.yonyou.iuap.jxzy.servlet.dao.DeviceMapper;
import com.yonyou.iuap.jxzy.utils.HttpRequestUtil;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yonyou.iuap.baseservice.ref.service.RefCommonService;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

import javax.transaction.Transactional;

import static com.yonyou.iuap.baseservice.intg.support.ServiceFeature.*;
@Service

/**
 * MonitorSample CRUD 核心服务,提供逻辑删除/乐观锁
 */
public class MonitorSampleService extends GenericIntegrateService<MonitorSample>{

	private Logger logger = LoggerFactory.getLogger(MonitorSampleService.class);

	public static final String LEDURL = "http://164.70.12.29:8080/unattended_hardware/hardwareOperation/showLedJX";

	@Autowired
	private DeviceMapper deviceMapper;

	private MonitorSampleMapper monitorSampleMapper;

	@Autowired
	public void setMonitorSampleMapper(MonitorSampleMapper monitorSampleMapper) {
		this.monitorSampleMapper = monitorSampleMapper;
		super.setGenericMapper(monitorSampleMapper);
	}

	@Autowired
	private RefCommonService refService;
	public List selectListByExcelData(List idsList) {
		List list  = monitorSampleMapper.selectListByExcelData(idsList);
		list = refService.fillListWithRef(list);
		return list;
	}


	/**
	 * @CAU 可插拔设计
	 * @return 向父类 GenericIntegrateService 提供可插拔的特性声明
	 */
	@Override
	protected ServiceFeature[] getFeats() {
		return new ServiceFeature[]{ REFERENCE,BPM,LOGICAL_DEL,DATA_PERMISSION };
	}

	/**
	 * 核查货物总数
	 * @param id
	 * @param columnNo
	 * @param rowNo
	 * @param layerNo
	 * @param goodsSum
	 * @return
	 * @throws BusinessException
	 */
	@Transactional
	public String updateParamByPoundNo(String id,String columnNo, String rowNo,
			String layerNo, String goodsSum) throws BusinessException {
		JSONObject jsonObject=new JSONObject();
		Integer update1=0;
		Integer update2=0;
		String pk_delivery=null;//收货通知主键  根据磅单表的主键，获取子表的主键，然后根据主表的主键关联收货通知单的主键，获取vdef5（3排3列2层）
		try {
			pk_delivery=monitorSampleMapper.getPkDeliver(id);
			String vdef5=rowNo+"排"+columnNo+"列"+layerNo+"层".toString();
			//随机排数
			int rownum=Integer.parseInt(rowNo);
			int column=Integer.parseInt(columnNo);
			if (rownum==0 || column==0){
				throw new BusinessException("排列异常:");
			}
			int[] rownumorgin=new int[rownum];
			int[] rownums=new int[2];
			int[] rowcolumns=new int[column];

			for(int i=0;i<rownumorgin.length;i++){
				rownumorgin[i]=(rownum-i);
			}

			int max = 0;
			int maxIndex = 0;
			for (int i = 0; i < rownumorgin.length; i++) {
				if (rownumorgin[i] > max) {
					max = rownumorgin[i];
					maxIndex = i+1;
				}
			}
			rownums[0]=max;
			rownums[1]=maxIndex;

			for(int i=0;i<rowcolumns.length;i++){
				rowcolumns[i]=(column-i);
			}
			//随机排数
			int rowrandom = (int) (rownums[new Random().nextInt(rownums.length)]);
			//获取取样列数
			int count=Integer.parseInt(goodsSum);
			ArrayList<Integer> columnrandoms =new ArrayList<Integer>();
			for(int i=0;i<count;i++){
				int columnrandom = rowcolumns[new Random().nextInt(rowcolumns.length)];
				/*if(columnrandoms.contains(columnrandom)){
					columnrandom = rowcolumns[new Random().nextInt(rowcolumns.length)];
				}*/
				columnrandoms.add(columnrandom);
			}
			Random random=new Random();
			int randomElement = columnrandoms.get(random.nextInt(columnrandoms.size()));
			StringBuffer sb=new StringBuffer();
			sb.append(rowrandom+"排"+randomElement+"列");
			/*for(int i=0;i<columnrandoms.size();i++){
				sb.append(columnrandoms.get(i));
				if(i+1!=columnrandoms.size()){
					sb.append("、");
				}else{
					sb.append("列");
				}
			}*/
			String vdef6=sb.toString();

			//String vdef6=rowNo+"排"+columnNo+"列".toString();//抽样位置显示排和列
			update2=monitorSampleMapper.updateParamById(id,goodsSum,vdef6); //更新磅单表  根据id更新总包数，抽样位置2个字段
			if (update2>0 && vdef5!=null) {
				update1=monitorSampleMapper.updateParamByPoundNo(pk_delivery,vdef5); //更新通知表
			}
			jsonObject.put("message", "通知表："+update1+"条，磅单表成功："+update2+"条");
		} catch (Exception e) {
			throw new BusinessException("核查货物总数异常:"+e.getMessage());
		}
		jsonObject.put("success", "success");
		return jsonObject.toString();
	}


	@Transactional
	public String sampleToAdd(MonitorSample monitorSample) throws BusinessException {
		JSONObject jsonObject=new JSONObject();
		int updateStatus=0;
		int updateParam=0;
		String pk_poundbill=monitorSample.getPk_poundbill();//磅单pk
		String samplingarea=monitorSample.getSamplingArea();//抽样区
		String vvehicle=monitorSample.getVvehicle();//车牌号
		String samplinglocation=monitorSample.getSamplingLocation();//抽样位置
		String[] str =monitorSample.getPumpingPosition();//加抽位置
		StringBuffer sb=new StringBuffer();
		for(int i=0;i<str.length;i++){
			if(i!=str.length-1){
				sb.append(str[i]+",");
			}else{
				sb.append(str[i]);
			}
		}
		String  pumpingPosition=sb.toString();//monitorSample.setPumpingPosition(Arrays.toString(str));
		try {
			updateParam= monitorSampleMapper.sampleToAdd(pk_poundbill,pumpingPosition);
			logger.error("加抽更新条数"+updateParam+"磅单主键:"+pk_poundbill);
			if (updateParam>0) {
				updateStatus= monitorSampleMapper.sampleToAddStatus(pk_poundbill);//更改状态
				logger.error("加抽状态更新条数"+updateStatus+"磅单主键:"+pk_poundbill);
			}
			if(updateParam==1 && updateStatus==1 && samplingarea!=null && !"~".equals(samplingarea)){//操作成功后显示到led
				//根据抽样区查询设备明细获取led设备
				List<DeviceInfo> deviceInfoList=this.deviceMapper.queryLEDDeviceVO(samplingarea);
				if(deviceInfoList!=null &&deviceInfoList.size()>0){
					this.processorled(deviceInfoList,samplingarea,vvehicle,pumpingPosition,samplinglocation);
				}
			}
			jsonObject.put("message", "磅单子表："+updateParam+"条，磅单表成功："+updateStatus+"条");
		} catch (Exception e) {
			throw new BusinessException("核查货物总数异常:"+e.getMessage());
		}
		jsonObject.put("success", "success");
		return jsonObject.toString();
	}


	/**
	 * 审核
	 * @param monitorSample
	 * @return
	 */
	@Transactional
	public Integer auditPass(MonitorSample monitorSample) {
		String pk_poundbill=monitorSample.getPk_poundbill();
		String samplingarea=monitorSample.getSamplingArea();//抽样区
		String vvehicle=monitorSample.getVvehicle();
		//审核时，更改磅单子表审核状态vbdef9 审核时间：磅单主表
		int result= monitorSampleMapper.auditPass(pk_poundbill);
		int resultForTime=monitorSampleMapper.updateAuditTime(pk_poundbill);
		logger.error("审核更新条数"+result+"磅单主键:"+pk_poundbill);
		if(result==1){//审核通过
			//根据抽样区查询设备明细获取led设备
			if(samplingarea!=null){
				List<DeviceInfo>  deviceInfoList=this.deviceMapper.queryLEDDeviceVO(samplingarea);
				if(deviceInfoList!=null &&deviceInfoList.size()>0){
					for(DeviceInfo dInfo:deviceInfoList) {
						String location=dInfo.getExtendClass();
						if(dInfo.getDeviceCode()!=null && dInfo.getDeviceCode().length()>0){
							//抽样区LED
							if ("抽样区".equals(location)){
								this.sendToLED(dInfo.getDeviceCode(),"请【"+vvehicle+"】前往待检区");
							}else if("办公室".equals(location)){
								this.sendToLED(dInfo.getDeviceCode(),"请前往待检区");
							}
						}
					}
				}
			}
		}
		return result;
	}


	/**
	 * 不加抽样本：抽样区led显示：车牌号+抽样位置
	 * 办公室led显示：抽样区+抽样位置
	 * @param monitorSample
	 * @return
	 */
	public String notSampleToAdd(MonitorSample monitorSample) {
		JSONObject jsonObject=new JSONObject();
		try {
			String samplingarea=monitorSample.getSamplingArea();//抽样区
			String vvehicle=monitorSample.getVvehicle();//车牌号
			String samplinglocation=monitorSample.getSamplingLocation();//抽样位置
			String totalPackageNo = monitorSample.getTotalPackageNo();//总包数
			if (monitorSample.getPk_poundbill()!=null) {
				Integer num=monitorSampleMapper.notSampleToAdd(monitorSample.getPk_poundbill());
				logger.error("不加抽更新条数:"+num+"磅单主键:"+monitorSample.getPk_poundbill());
			}
			//根据抽样区查询设备明细获取led设
			List<DeviceInfo> deviceInfoList=null;
			if(samplingarea!=null){
				deviceInfoList=this.deviceMapper.queryLEDDeviceVO(samplingarea);
			}
			if(deviceInfoList!=null &&deviceInfoList.size()>0){
				this.notSampleToled(deviceInfoList,samplingarea,vvehicle,samplinglocation,totalPackageNo);
			}
		} catch (Exception e) {
			jsonObject.put("message", "不加抽LED显示异常");
			jsonObject.put("success", "error");
		}
		jsonObject.put("message", "不加抽LED显示成功");
		jsonObject.put("success", "success");
		return jsonObject.toString();
	}

	/**
	 * 不加抽显示到led
	 * @param deviceInfoList
	 * @param auditstatus
	 * @param samplingarea
	 * @param vvehicle
	 * @param samplinglocation
	 * @return
	 */
	private void notSampleToled(List<DeviceInfo> deviceInfoList,
			String samplingarea, String vvehicle, String samplinglocation,String totalPackageNo) {
		String ledText=null;//led显示
		if (deviceInfoList.size()>0) {
			//获取led设备信息
			for(DeviceInfo dInfo:deviceInfoList) {
				String location=dInfo.getExtendClass();
				//抽样区LED
				if ("抽样区".equals(location)){
					//TODO 文本加上总包数
					ledText=vvehicle+"\n抽样位置:"+samplinglocation+"\n总包数:"+totalPackageNo;
					//判断LED设备编码是否存在
					if(dInfo.getDeviceCode()!=null && dInfo.getDeviceCode().length()>0){
						this.sendToLED(dInfo.getDeviceCode(), ledText);
					}
				}else if("办公室".equals(location)){
					ledText=samplingarea+"\n抽样位置:"+samplinglocation;
					if(dInfo.getDeviceCode()!=null && dInfo.getDeviceCode().length()>0){
						this.sendToLED(dInfo.getDeviceCode(), ledText);
					}
				}
			}
		}
	}


	/**
	 *加抽样本：抽样区led显示：车牌号+抽样位置+加抽位置
	 *办公室led显示：抽样区+抽样位置+加抽位置
	 * @param samplinglocation2 
	 */
	public void processorled(List<DeviceInfo> deviceInfoList,String samplingarea, 
			String vvehicle, String pumpingPosition, String samplinglocation) throws BusinessException {
		String ledText=null;//led显示
		if (deviceInfoList.size()>0) {
			//获取led设备信息
			for(DeviceInfo dInfo:deviceInfoList) {
				String location=dInfo.getExtendClass();
				//抽样区LED
				if ("抽样区".equals(location)){
					//加抽位置是否为空
					if (pumpingPosition!=null) {
						ledText=vvehicle+"\n抽样位置:"+samplinglocation+"\n加抽位置:"+pumpingPosition;
					}else{
						ledText=vvehicle+"\n抽样位置:"+samplinglocation;
					}
					//判断LED设备编码是否存在
					if(dInfo.getDeviceCode()!=null && dInfo.getDeviceCode().length()>0){
						this.sendToLED(dInfo.getDeviceCode(), ledText);
					}
				}else if("办公室".equals(location)){
					//加抽位置是否为空
					if (pumpingPosition!=null) {
						ledText=samplingarea+"\n抽样位置:"+samplinglocation+"\n加抽位置:"+pumpingPosition;
					}else{
						ledText=samplingarea+"\n抽样位置:"+samplinglocation;
					}
					if(dInfo.getDeviceCode()!=null && dInfo.getDeviceCode().length()>0){
						this.sendToLED(dInfo.getDeviceCode(), ledText);
					}
				}
			}
		}

	}

	public String sendToLED(String deviceCode,String LedText){
		JSONObject json=new JSONObject();
		json.put("deviceCode", deviceCode);
		json.put("ledText", LedText);
		String result=HttpRequestUtil.sendPost2(LEDURL, json.toString());
		if("".equals(result)|| Boolean.FALSE.equals(new Boolean(result))){
			logger.error("LED显示异常");
		}else{
			logger.error("led显示成功："+LedText+"led编码："+deviceCode);
		}
		return result;

	}


	public Integer changeStatus(String pk_poundbill, String humanVerifyFlag) {
		return monitorSampleMapper.changeSdtatus(pk_poundbill);
	}
	
	public List<MonitorSample> queryBypk(String pk_poundbill) {
		return monitorSampleMapper.queryBypk(pk_poundbill);
	}

}
